import { useEffect, useState, useRef } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import loadable from '@loadable/component';
import { Button, Popover, Badge, Avatar, Skeleton, App } from 'antd';
import { SolutionOutlined, UserOutlined, WalletOutlined, LogoutOutlined, MessageOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';

import { setStore } from '@/reducers/common';
import { logout } from '@/service/base';
import { HOME, ACCOUNT } from '@/config/url';
import styles from './index.module.scss';

export default props => {
    const initState = () => ({
        open: false,
    });
    const [state, setState] = useState(initState);
    const { message } = App.useApp();
    const { userInfo={} } = useSelector(s => s.common || {});
    const unReadCount =  0;
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const isVip = 1 !== userInfo?.memberVipId;

    // 登录
    const toLogin = () => {
        dispatch(setStore({loginVisible: true}));
    };
    // 个人中心
    const toAccount = () => {
        setState(o => ({...o, open: false}));
        navigate(`${ACCOUNT}?uid=${userInfo?.id||''}`);
    };
    // 退出登录
    const toLogout = async () => {
        // 清除 localStorage
        await logout();

        // 清除 localStorage
        localStorage.removeItem('accessToken');
        dispatch(setStore({userInfo: {}}));

        message.success(`已退出登录，即将跳转至首页`);
        setState(o => ({...o, open: false}));

        let t = setTimeout(() => {
            clearTimeout(t);

            location.href = HOME;
        }, 2000);
    };
    // 打开vip弹框
    const handleShowPay = () => {
        setState(o => ({...o, open: false}));

        if(!userInfo?.id) return toLogin();

        dispatch(setStore({payVisible: true}));
    };
    // 显示/隐藏
    const onOpenChange = open => {
        setState(o => ({...o, open}));
    };
    // 弹框内容
    const popoverContent = () => {
        return (
            <div className={styles['popover-body']}>
                <div className={styles['user-info']}>
                    <div className={styles['user-avatar']}><img src={userInfo?.avatar ? `${userInfo?.avatar}?x-oss-process=image/resize,p_40` : '/images/default-avatar.png'}/></div>
                    <div className={styles['name']}>
                        <p className={styles['n1']}>{userInfo?.nickName || "--"}</p>
                    </div>
                </div>
                <div className={styles['menu']}>
                    <div className={styles['menu-item']} onClick={toAccount}><span><UserOutlined /></span>用户中心</div>
                    <div className={styles['menu-item']} onClick={toLogout}><span><LogoutOutlined /></span>退出登录</div>
                </div>
            </div>
        );
    };

    return (
        <>
            {
                !!userInfo?.id ?
                    <Popover
                        content={popoverContent()}
                        title=""
                        trigger={['click']}
                        open={state.open}
                        onOpenChange={onOpenChange}
                        rootClassName={styles['popover-container']}
                        arrow={false}
                        placement='bottomRight'
                    >
                        <div className={styles['avatar']}>
                            <Badge count={unReadCount} size="small" overflowCount={10}>
                                <Avatar className={styles['avatar-image']} src={userInfo?.avatar ? `${userInfo?.avatar}?x-oss-process=image/resize,p_40` : '/images/default-avatar.png'} />
                            </Badge>
                        </div>
                    </Popover>
                    :
                    <Button className={styles['login-button']} type="primary" shape="round" onClick={toLogin} icon={<UserOutlined/>}>登录</Button>
            }
        </>
    )
}
